package pri.zxx.nio;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import pri.zxx.webdemo.config.ExPrint;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Base64;

/**
 * @author Twilight
 * @desc
 * @createTime 2020-05-16-18:58
 */
@Slf4j
public class Base64Test {
    @Test
    public void test() throws IOException {
        Path originalPath = Paths.get("d:/", "data.txt");
        Path targetPath = Paths.get("d:/", "base.txt");

        Base64.Encoder mimeEncoder = Base64.getMimeEncoder();
        try (OutputStream output = Files.newOutputStream(targetPath)) {
            if (Files.notExists(originalPath)) {
                Files.createFile(originalPath);
            }
            if (Files.notExists(targetPath)) {
                Files.createFile(targetPath);
            }
            //Copy the encoded file content to target file
            Files.copy(originalPath, mimeEncoder.wrap(output));
            //Or simply use the encoded output stream
//            OutputStream encodedStrem = mimeEncoder.wrap(output);
        } catch (Exception e) {
            log.error("nio异常{}", ExPrint.print(e));
        }
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(Files.readAllBytes(targetPath));
        System.out.println(new String(decode));
    }

    private void pringExByLog(Exception e) {
        long st1 = Instant.now().toEpochMilli();
        for (int i = 0; i < 10000; i++) {
            log.error("nio异常{}", ExPrint.print(e));
        }
        System.out.println(Instant.now().toEpochMilli() - st1);
    }

    private void pringExByStack(Exception e) {
        long st = Instant.now().toEpochMilli();
        for (int i = 0; i < 10000; i++) {
            e.printStackTrace();
        }
        System.out.println(Instant.now().toEpochMilli() - st);
    }
}
